package com.xsd.xsdhouduan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xsd.xsdhouduan.entity.PlatformIncome;
import com.xsd.xsdhouduan.entity.Task;
import com.xsd.xsdhouduan.mapper.PlatformIncomeMapper;
import com.xsd.xsdhouduan.service.PlatformIncomeService;
import com.xsd.xsdhouduan.service.TaskService;
import com.xsd.xsdhouduan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 平台收入服务实现类
 */
@Service
public class PlatformIncomeServiceImpl extends ServiceImpl<PlatformIncomeMapper, PlatformIncome> implements PlatformIncomeService {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    @Lazy
    private TaskService taskService;
    
    @Override
    @Transactional
    public boolean recordPublishFee(Long taskId, Long publisherId, BigDecimal amount) {
        PlatformIncome income = new PlatformIncome();
        income.setTaskId(taskId);
        income.setPublisherId(publisherId);
        income.setAmount(amount);
        income.setType(1); // 任务发布费
        income.setStatus(0); // 待结算
        
        return save(income);
    }
    
    @Override
    @Transactional
    public boolean recordCompleteFee(Long taskId, Long accepterId, BigDecimal amount) {
        // 获取任务信息以获取发布者ID
        Task task = taskService.getById(taskId);
        if (task == null) {
            return false;
        }
        
        PlatformIncome income = new PlatformIncome();
        income.setTaskId(taskId);
        income.setPublisherId(task.getPublisherId()); // 设置发布者ID
        income.setAccepterId(accepterId);
        income.setAmount(amount);
        income.setType(2); // 任务完成费
        income.setStatus(0); // 待结算
        
        return save(income);
    }
    
    @Override
    @Transactional
    public boolean recordPlatformFee(Long taskId, Long publisherId, BigDecimal taskReward) {
        PlatformIncome income = new PlatformIncome();
        income.setTaskId(taskId);
        income.setPublisherId(publisherId);
        // 计算3%平台费
        BigDecimal platformFee = taskReward.multiply(new BigDecimal("0.03"));
        income.setAmount(platformFee);
        income.setType(3); // 平台费
        income.setPlatformRate(new BigDecimal("3.00")); // 3%费率
        income.setStatus(0); // 待结算
        return save(income);
    }
    
    @Override
    @Transactional
    public boolean settleIncome(Long incomeId) {
        PlatformIncome income = getById(incomeId);
        if (income != null && income.getStatus() == 0) {
            // 检查关联的任务是否已完成
            Task task = taskService.getById(income.getTaskId());
            if (task == null || task.getStatus() != 3) {
                System.out.println("DEBUG: 任务未完成，无法结算收入。任务ID: " + income.getTaskId() + ", 任务状态: " + (task != null ? task.getStatus() : "null"));
                return false;
            }
            
            // 更新状态为已结算
            income.setStatus(1);
            income.setSettlementTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            // 根据收入类型进行不同的处理
            if (income.getType() == 2 && income.getAccepterId() != null) {
                // 完成费：给接取者转账（97%的奖励）
                userService.addBalance(income.getAccepterId(), income.getAmount());
                System.out.println("DEBUG: 给接取者转账: " + income.getAmount() + ", 接取者ID: " + income.getAccepterId());
            } else if (income.getType() == 1) {
                // 发布费：平台收入，不需要转账
                System.out.println("DEBUG: 记录发布费收入: " + income.getAmount());
            } else if (income.getType() == 3) {
                // 平台费：平台收入，不需要转账
                System.out.println("DEBUG: 记录平台费收入: " + income.getAmount());
            }
            
            // 结算后逻辑删除（标记为已删除）
            income.setDeleted(1);
            
            return updateById(income);
        }
        return false;
    }
    
    @Override
    public BigDecimal getTotalIncome() {
        LambdaQueryWrapper<PlatformIncome> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PlatformIncome::getDeleted, 0); // 未删除的所有收入
        
        List<PlatformIncome> incomes = list(wrapper);
        return incomes.stream()
                .map(PlatformIncome::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
    
    @Override
    public List<PlatformIncome> getPendingSettlement() {
        LambdaQueryWrapper<PlatformIncome> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PlatformIncome::getStatus, 0) // 待结算
                .eq(PlatformIncome::getDeleted, 0) // 未删除
                .orderByDesc(PlatformIncome::getCreateTime);
        
        List<PlatformIncome> incomes = list(wrapper);
        return incomes.stream().map(this::populateIncomeDetails).collect(Collectors.toList());
    }
    
    @Override
    public List<PlatformIncome> getSettledIncome() {
        LambdaQueryWrapper<PlatformIncome> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PlatformIncome::getStatus, 1) // 已结算
                .eq(PlatformIncome::getDeleted, 1) // 已删除（结算后标记为已删除）
                .orderByDesc(PlatformIncome::getSettlementTime);
        
        List<PlatformIncome> incomes = list(wrapper);
        return incomes.stream().map(this::populateIncomeDetails).collect(Collectors.toList());
    }
    
    /**
     * 填充收入详情
     */
    private PlatformIncome populateIncomeDetails(PlatformIncome income) {
        // 填充发布者信息
        if (income.getPublisherId() != null) {
            var publisher = userService.getById(income.getPublisherId());
            if (publisher != null) {
                income.setPublisherName(publisher.getName());
                System.out.println("DEBUG: 填充发布者信息 - ID: " + income.getPublisherId() + ", 姓名: " + publisher.getName());
            } else {
                System.out.println("DEBUG: 发布者不存在 - ID: " + income.getPublisherId());
            }
        }
        
        // 填充接取者信息
        if (income.getAccepterId() != null) {
            var accepter = userService.getById(income.getAccepterId());
            if (accepter != null) {
                income.setAccepterName(accepter.getName());
                System.out.println("DEBUG: 填充接取者信息 - ID: " + income.getAccepterId() + ", 姓名: " + accepter.getName());
            } else {
                System.out.println("DEBUG: 接取者不存在 - ID: " + income.getAccepterId());
            }
        } else {
            System.out.println("DEBUG: 接取者ID为空 - 收入ID: " + income.getId() + ", 类型: " + income.getType());
        }
        
        // 填充任务信息
        Task task = taskService.getById(income.getTaskId());
        if (task != null) {
            income.setTaskTitle(task.getTitle());
            income.setTaskStatus(task.getStatus());
            
            // 如果PlatformIncome的accepterId为空，但从Task中获取到了接取者信息，则填充接取者信息
            if (income.getAccepterId() == null && task.getAccepterId() != null) {
                var accepter = userService.getById(task.getAccepterId());
                if (accepter != null) {
                    income.setAccepterName(accepter.getName());
                    System.out.println("DEBUG: 从任务中填充接取者信息 - 任务ID: " + task.getId() + 
                        ", 接取者ID: " + task.getAccepterId() + ", 接取者姓名: " + accepter.getName());
                }
            }
        } else {
            income.setTaskTitle("任务ID: " + income.getTaskId());
            income.setTaskStatus(-1); // 任务不存在
        }
        
        return income;
    }
}
